﻿using System;
using System.Web.Mvc;
using System.Web.SessionState;
using ControllerExtensibility.Controllers;

namespace ControllerExtensibility.Infrastructure
{
    public class CustomControllerFactory : IControllerFactory
    {
        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            Type targetType;
            switch (controllerName.ToLower())
            {
                case "product":
                    targetType = typeof(ProductController);
                    break;

                case "customer":
                    targetType = typeof(CustomerController);
                    break;
                case "remotedata":
                    targetType = typeof(RemoteDataController);
                    break;

                default:
                    requestContext.RouteData.Values["Controller"] = "Product";
                    targetType = typeof(ProductController);
                    break;
            }
            return (IController)DependencyResolver.Current.GetService(targetType);
        }

        public SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            return SessionStateBehavior.Default;
        }

        public void ReleaseController(IController controller)
        {
            var disposable = controller as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
    }
}